<?php


namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\User;
use app\api\model\UserAddress;
use app\api\service\Token;
use app\api\validate\AddressNewValidate;
use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\successMessage;
use app\lib\exception\TokenException;
use app\lib\exception\UserException;
use think\Controller;

class AddressController extends BaseController{

    //tp5的前置方法
    protected  $beforeActionList = [
        'checkPrimaryScope'=>['only'=>'createOrUpdateAddress,getUserAddress']
    ];

    public function createOrUpdateAddress(){
        $validate = new AddressNewValidate();
        $validate->goCheck();
        /**
         * 根据Token 获取uid
         * 根据uid来查找用户数据，判断用户是否存在，如果不存在在抛出异常
         * 获取用户从客户端提交的地址信息
         * 根据用户地址信息是否存在，从而判断是添加还是修改地址
         */
        $uid = Token::getCurrentUid();
        $user = new User();
        $userlist = $user::get($uid);
        if(!$userlist){
            throw new UserException();
        }

        $userAddress = $userlist->address;
        //$res = $userAddress->toArray();

        //收集前端传递回来的数据
        $dataArray = $validate->getDataByRule(input('post.'));

        if(!$userAddress){
            $userlist->address()->save($dataArray);
        }else{
            $userlist->address->save($dataArray);
        }

        return json(new successMessage(),201);
    }



    //获取用户地址
    public function getUserAddress(){
        $uid = Token::getCurrentUid();
        $addressModel = new UserAddress();
        $userAddress = $addressModel->where('user_id',$uid)->find();
        if(!$userAddress){
            throw new UserException(['msg'=>'用户地址不存在','errorCode'=>60001]);
        }

        return json($userAddress);
    }




}